package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    public static List<RpcClient> list = new ArrayList<>(2);

    public static Object createProxy(Class serviceClass, int order) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long startTime = System.currentTimeMillis();
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = list.get(order);
                        try {
                            //3.发送消息
                            System.out.println("请求客户端：" + rpcClient.getPath());
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            if(responseMsg == null) {
                                if(list.size() == 2) {//服务端下线，重试另一个服务端
                                    rpcClient = list.get((order + 1) % 2);
                                    System.out.println("重试另一个服务端：" + rpcClient.getPath());
                                    responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                                    if(responseMsg == null) {
                                        throw new RuntimeException("服务端已全部下线");
                                    }
                                } else if(list.size() == 1) {//另一个服务端也下线
                                    throw new RuntimeException("服务端已全部下线");
                                }
                            }
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            long endTime = System.currentTimeMillis();
                            System.out.println("服务端响应结果：" + result + ",路径为：" + rpcClient.getPath() +
                                    ",耗时:" + (endTime - startTime) + "ms,最后一次响应时间：" + endTime);
                            rpcClient.setCostTime((endTime - startTime));
                            rpcClient.setLastResponseTime(endTime);
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        }/* finally {
                            rpcClient.close();
                        }*/

                    }
                });
    }
}
